package com.itbaizhan.dao.impl.impl;

import com.itbaizhan.common.JdbcUtils;
import com.itbaizhan.dao.impl.UserDao;
import com.itbaizhan.exception.ApplicationException;
import com.itbaizhan.pojo.Items;
import com.itbaizhan.pojo.Orders;
import com.itbaizhan.pojo.Users;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/*接口实现类*/
//继承BaseDaoImpl 那么在UserDaoImpl也可以用BseDao方法，因为BaseDao变成父类
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
    /*根据用户ID查询用户*/
    @Override
    public Users selectUserById(int userid) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //如果给的userId在表中是有的，那在while循环中执行
        //如果userid没有，那返回一个空，方便判断
        Users users = null;

        try{
            connection = JdbcUtils.getConnection();
            ps = connection.prepareStatement("select * from users where userid = ? ");
            //绑定参数
            ps.setInt(1,userid);
            //执行语句
            rs = ps.executeQuery();
            while (rs.next()){
                //手动的ORM映射
                users = new Users();
                users.setUserid(rs.getInt("userid"));  ;
                users.setUsername(rs.getString("username")); ;
                users.setUserage(rs.getInt("userage"));

            }
        }catch (Exception e){
            e.printStackTrace();
            //自定义异常，增加偶合度
            throw new ApplicationException(e.getMessage());
        }finally {
            JdbcUtils.closeResource(rs,ps,connection);
        }
        return users;
    }
    //根据用户id修改信息
    //用BaseDao实现方法（通用的DML操作）
    //不用重复写try-catch等代码
    /*1，创建sql语句，2，给定数组参数(初始化数组)，在web(表述层实例化时再给实际参数)，3，调用BaseDao方法*/
    @Override
    public int updateUsersByiId(Users users) {
        String sql = "update users set userage = ? where userid = ?";
        //数组初始化
        Object[] param = new Object[]{users.getUserage(),users.getUserid()};
       //另一种初始化方式
        // Object[] param = {users.getUserage(),users.getUserid()};
       /*因为本类继承了BaseDao类，可以直接用this 调用
       * BaseDaoImpl类中的方法*/
        return this.executeUpdate(sql,param);
    }

    @Override
    public List<Users> selectUsersByLikeName(String username) {
       String sql = "select * from users where username like ?";
       Object[] param = new Object[]{"%"+username+"%"};
        return this.select(sql,param,Users.class);
    }
    /*对象关联查找*/
    @Override
    public Users selectUsers(int userid) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Users users = new Users();
        try{
           connection = JdbcUtils.getConnection();
           ps = connection.prepareStatement("select * from users u,orders o,order_items oi,items i WHERE\n" +
                   "u.userid = o.user_id and o.orderid = oi.order_id and oi.item_id = i.itemid\n" +
                   "and u.userid = ?");
           ps.setInt(1,userid);
           rs = ps.executeQuery();
           while(rs.next()){
               //将结果集映射到Users类中，在try外面实例化
               users.setUserid(rs.getInt("userid"));  ;
               users.setUsername(rs.getString("username")); ;
               users.setUserage(rs.getInt("userage"));
               //Orders 对象的ORM映射
               Orders orders = new Orders();
               orders.setOrderid(rs.getInt("orderid"));
               orders.setOrderprice(rs.getInt("orderprice"));
               //在Users类中创建了Orders的关联集合，将orders放进集合中
               users.getOrders().add(orders);
               //Items对象的映射
               Items items = new Items();
               items.setItemid(rs.getInt("itemid"));
               items.setItemname(rs.getString("itemname"));
               items.setItemprice(rs.getDouble("itemprice"));
               items.setItemnum(rs.getInt("itemnum"));
               //items在orders有关联，是集合形式，将items放入orders中
               orders.getItems().add(items);


           }
        }catch (Exception e){
            e.printStackTrace();
            throw new ApplicationException(e.getMessage());
        }finally {
            JdbcUtils.closeResource(rs,ps,connection);
        }
        //对象关联关系，将order放进users,将items放进orders，形成关联关系，
        // 所以返回users对象就可以
        return users;
    }
}
